<?php
/**
 * 用户参与矩阵
 */
namespace app\common\model;

use think\Db;
use think\Model;
use app\api\model\BaseConfig as BaseConfigModel;
use app\common\model\Member as MemberModel;
use app\common\model\UserMoneyLog as UserMoneyLogModel;
use app\common\common;

class MemberMatrix extends Model
{
    protected $name = 'member_matrix';

    /**
     * 用户参与矩阵
     * @param $mid  用户ID
     * @param $money    参与数量
     * @param $pay_type 支付方式 1:余额支付 2:链钱包支付
     * @param $type 参与币种
     * @return false|int|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function add($mid,$money,$pay_type,$type = 1){
        $multiple = BaseConfigModel::config_data('bonus_multiple');
        if(empty($multiple) || $multiple <= 0) return false;
        $data = [
            'mid'   =>  $mid,
            'type'  =>  $type,
            'money' =>  $money,
            'multiple' =>  $multiple,
            'bonus'  =>  bcmul($money,$multiple,2),
            'status'    =>  $pay_type == 1 ? 2 : 1, //判断是钱包支付还是余额支付
            'pay_type'  =>  $pay_type,
            'add_time'  =>  date('Y-m-d H:i:s',time()),
            'update_time'  =>  date('Y-m-d H:i:s',time())
        ];
        $id = self::insertGetId($data);

        if($id){
            if($pay_type == 1){ //增加奖励点
                UserMoneyLogModel::change($mid,'reward',$data['bonus'],'Matrix rewards',$id,'参与矩阵，支付：'.$money.'U,获得:'.$multiple.'倍奖励点,共:'.$data['bonus']);
            }
            return $id;
        }else{
            return false;
        }
    }

    /**
     * 查询参与矩阵记录详情
     * @param $mid  用户ID
     * @param $id   记录ID
     * @return MemberMatrix|array|mixed|Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getMemberDetails($mid,$id){
       $data = self::where('mid',$mid)->where('id',$id)->find();
       return $data;
    }

    /**
     * 查询用户参与记录
     * @param $mid  用户ID
     * @param int $page 页码
     * @param int $limit    每页数量
     * @param array $where  条件查询
     * @param string $order 排序
     * @return array
     * @throws \think\db\exception\DbException
     */
    public static function getUserList($mid,$page = 1,$limit = 20,$where = [],$order = 'id desc'){
        return self::where('mid',$mid)->where($where)->order($order)->paginate(['list_rows'=>$limit,'page'=>$page])->toArray();
    }

    /**
     * 统计用户矩阵奖励点
     * @param $mid  用户ID
     * @return array
     */
    public static function statistics($mid){
        $data = [];
        //总购买奖励点
        $data['bonus'] = self::where('mid',$mid)->sum('bonus');
        //已发放奖励点
        $data['returned'] = self::where('mid',$mid)->sum('returned');
        //剩余未发放奖励点
        $data['surplus'] = bcsub($data['bonus'],$data['returned'],2);
        return $data;
    }

    /**
     * 订单改为已支付
     * @param $mid  用户ID
     * @param $id   订单ID
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function update_paid($mid,$id){
        
        $details = self::getMemberDetails($mid,$id);

        if(empty($details)) return false;
        
        $details = $details->toArray();
        
        if($details['status'] != 1) return false;
        $where = [
            'mid'    =>  $mid,
            'id'    =>  $id,
        ];
        
        //赠送积分

        try {
            $data = [];
            $info = self::where($where)->find();
            $data['username'] = \app\api\model\Member::where('id', $mid)->value('username');
            $data['point'] = $info['money'];
            $data['time'] = time();
            $data['key'] = '666789';
            $data2 = $data;
            sort($data2);
            $data['sign'] = md5(http_build_query($data2));
            unset($data['key']);
            $data = base64_encode(json_encode($data));

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, "https://wap.mmstio.com/api/register/point?data=".$data);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
            $output = curl_exec($ch);
            curl_close($ch);
            $res = json_decode($output,true);
            if($res['code'] == 0){
                self::where($where)->update(['point'=>2]);
            }
        }catch(\Exception $e){

        }

        //改为已支付
        self::where($where)->update(['status'=>2,'update_time'=>date('Y-m-d H:i:s',time())]);
        
        //发放矩阵奖励
        common::juzhenjiangli($id,$details['money'],$mid);
        
        return true;
    }

    /**
     * 统计某一天新购买矩阵或返回的奖励点
     * @param $day  日期 Y-N-D
     * @return array
     */
    public static function yesterday_newadd($day){
       //新增奖励点
       $data['bonus']  = self::where('add_time','between',[$day.' 00:00:00',$day.' 23:59:59'])->where('status','>','1')->sum('bonus');
       //支付金额
       $data['money']  = self::where('add_time','between',[$day.' 00:00:00',$day.' 23:59:59'])->where('status','>','1')->sum('money');
       return $data;
    }

    /**
     * 统计所有
     * @return array
     */
    public static function total_all(){
        //总奖励点
        $data['bonus'] = self::where('status','>','1')->sum('bonus');
        //总已释放奖励点
        $data['returned'] = self::where('status','>','1')->sum('returned');
        //总参与金额
        $data['money'] = self::where('status','>','1')->sum('money');
        return $data;
    }
}